#include <copydir.h>
//多线程复制
void *pthread_copy_file(void *arg) {
	struct pthread_block *block = (struct pthread_block *)arg;
	char buf[BUFF_SIZE];
	int ret;
	size_t count = block->start;
	ret = lseek(block->fd1, block->start, SEEK_SET);
	ret = lseek(block->fd2, block->start, SEEK_SET);
	
	int bytes_read,bytes_write;
	while (count < block->end) {
		bytes_read = read(block->fd1, buf, BUFF_SIZE);
		if (bytes_read > 0) {
			count += bytes_read;
			if (bytes_read == -1&&errno != EINTR) {
				break;
			}
			bytes_write = write(block->fd2, buf, bytes_read);
		}
	}

	pthread_exit(NULL);
}

size_t get_filesize(int fd) {
	struct stat st;
	fstat(fd,&st);
	return st.st_size;
}
//文件复制
void copy_file(char *file1, char *file2) {
	int fd1,fd2;
	fd1 = open(file1,O_RDONLY);
	if(fd1 == -1){
		perror("open file1");
		exit(1);
	}
	
	fd2 = open(file2,O_WRONLY|O_CREAT|O_TRUNC,0644);
	if(fd2 == -1){
		perror("open file2");
		exit(1);
	}
	
	size_t file_size = get_filesize(fd1);
	size_t part_size = COUNT;
	struct pthread_block *block = (struct pthread_block *)malloc(sizeof(struct pthread_block) * part_size);
	size_t percent = file_size/part_size;
	int i;
	for (i = 0; i < part_size; i++) {
		block[i].fd1 = fd1;
		block[i].fd2 = fd2;
		block[i].start = i * percent;
		if(i == part_size-1) {
			block[i].end = file_size;
		} else {
			block[i].end = block[i].start + percent;
		}
	}
	pthread_t ptid[part_size];
	
	for (i = 0; i < part_size; i++) {
		pthread_create(&ptid[i], NULL, pthread_copy_file, &block[i]);
	}
	for (i = 0; i < part_size; i++) {
        	pthread_join(ptid[i],NULL);
    	}
    	free(block);
    	close(fd1);
    	close(fd2);
    	FILE *f = fopen("./pro_copy.log","a+");
	time_t rawtime;
	struct tm *timeinfo;
	timeinfo = localtime(&rawtime);
	fprintf(f,"\007The current date/time is:%s\n",asctime(timeinfo));
	fprintf(f,"copy file %s --> %s\n",file1, file2);
	fclose(f);
}
